#ifndef SQLTEXTEDIT_H
#define SQLTEXTEDIT_H

#include <QPlainTextEdit>

class SqlTextEdit : public QPlainTextEdit
{
    Q_OBJECT

public:
    explicit SqlTextEdit(QWidget *parent = nullptr);
    
    // 重写父类方法以支持代码折叠
    void lineNumberAreaPaintEvent(QPaintEvent *event);
    int lineNumberAreaWidth();
    
protected:
    void resizeEvent(QResizeEvent *event) override;
    void keyPressEvent(QKeyEvent *e) override;

private slots:
    void updateLineNumberAreaWidth(int newBlockCount);
    void highlightCurrentLine();
    void updateLineNumberArea(const QRect &rect, int dy);
    void toggleBlockFold();
    void foldCurrentBlock();
    void unfoldCurrentBlock();
    
private:
    QWidget *lineNumberArea;
    QMap<int, bool> foldedBlocks;  // 记录折叠的代码块
    
    // 辅助方法
    bool isFoldableBlock(const QTextBlock &block) const;
    int findBlockEnd(const QTextBlock &startBlock) const;
    void foldBlock(int blockNumber);
    void unfoldBlock(int blockNumber);
    void updateFoldIndicator(int blockNumber);
};

// 行号区域类
class LineNumberArea : public QWidget
{
public:
    LineNumberArea(SqlTextEdit *editor) : QWidget(editor), codeEditor(editor)
    {}

    QSize sizeHint() const override
    {
        return QSize(codeEditor->lineNumberAreaWidth(), 0);
    }

protected:
    void paintEvent(QPaintEvent *event) override
    {
        codeEditor->lineNumberAreaPaintEvent(event);
    }
    
    void mousePressEvent(QMouseEvent *event) override;

private:
    SqlTextEdit *codeEditor;
};

#endif // SQLTEXTEDIT_H